# -*- coding:utf-8 -*-
import pymysql
from functools import wraps
from ElevatorAdmin import settings


def singleton(cls):
    """ 装饰器singleton """
    instances = {}

    @wraps(cls)
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance


@singleton
class MySQLSingle(object):
    """ mysql 单例 """
    def __init__(self):
        self.host = settings.DATABASES['default']['HOST']
        self.user = settings.DATABASES['default']['USER']
        self.port = settings.DATABASES['default']['PORT']
        self.password = settings.DATABASES['default']['PASSWORD']
        self.db = settings.DATABASES['default']['NAME']

    def get_conn(self):
        try:
            connection = pymysql.connect(host=self.host,
                                         user=self.user,
                                         password=self.password,
                                         db=self.db,
                                         charset='utf8mb4',
                                         port=int(self.port),
                                         cursorclass=pymysql.cursors.DictCursor)
        except Exception as e:
            print('File to connect database: %s' % e)
            connection = None
        return connection
